package com.ynet.middleground.user.model;

import java.time.LocalDateTime;
import java.util.*;

import org.apache.commons.lang.StringUtils;
import org.dozer.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ynet.core.common.PagerInfo;
import com.ynet.core.exception.BusinessException;
import com.ynet.middleground.user.bean.*;
import com.ynet.middleground.user.common.ErrorMessageConstant;
import com.ynet.middleground.user.common.SystemConstant;
import com.ynet.middleground.user.dao.*;
import com.ynet.middleground.user.dto.*;
import com.ynet.middleground.user.entity.*;
import com.ynet.middleground.user.utils.BeanUtil;
import com.ynet.middleground.user.utils.CommUtils;
import com.ynet.middleground.user.utils.GeneralService;

/**
 * @program: 2019-10-12_userCenter
 * @description: 组织管理事务
 * @author: DaiGaoLe
 * @create: 2019-10-23 17:55
 **/
@Component
public class OrganizationManagementModel extends ServiceImpl<UserBaseInformationMapper, UserBaseInformation> {

    @Autowired
    EmployeeInformationMapper employeeInformationMapper;

    @Autowired
    private Mapper dozerBeanMapper;

    @Autowired
    private OrganizationalRoleRelationMapper organizationalRoleRelationMapper;

    @Autowired
    private OrganizationalStructureMapper organizationalStructureMapper;

    @Autowired
    InPortRoleMapper inPortRoleMapper;

    @Autowired
    private CommUtilsMapper commUtilsMapper;

    @Autowired
    UserBaseInformationHistoryMapper userBaseInformationHistoryMapper;

    @Autowired
    EmployeeInformationHistoryMapper employeeInformationHistoryMapper;

    @Autowired
    UserBaseInformationMapper userBaseInformationMapper;

    @Autowired
    GeneralService generalService;

    @Autowired
    private EnterpriseUserInfoMapper enterpriseUserInfoMapper;

    @Autowired
    private OrganizationalStructureHistoryMapper organizationalStructureHistoryMapper;

    @Autowired
    private RoleManagementModel roleManagementModel;

    // 上传多渠道的话，约定以“,”隔开，例：C01,C02；
    private static final String queryChannelSplitFlag = ",";

    /* 添加港内员工事 begin */

    /**
     * @program: 2019-10-12_userCenter
     * @description: 添加港内员工事务层、 注意，同一个港内员工若想在不同渠道维护信息，只有在第一个渠道添加信息时候，调用“港内员工数据添加”接口，
     *               在其他渠道维护信息时候，需要调用"港内员工组织机构、部门、角色关系维护"接口
     * @author: DaiGaoLe
     * @create: 2019-10-23 15:57
     **/
    @Transactional(rollbackFor = Exception.class)
    public Integer addEmployee(AddEmployeeReq requestObject) {
        // 声明变量 begin
        Integer operationUserId = new Integer(requestObject.getOperationUserId());
        String channel = requestObject.getChannel();
        String userAccounts = requestObject.getUserAccounts();
        String userPassword = requestObject.getUserPassword();
        List<EmployeeInformation> employees = new ArrayList<>();
        List<UserBaseInformation> baseInformations = new ArrayList<>();
        String flag = requestObject.getFlag();
        String salt = CommUtils.getSalt();
        String telephone = requestObject.getTelephone();
        String userName = requestObject.getUserName();
        String employeeNo = requestObject.getEmployeeNo(); // 员工编号
        // UserBaseInformation operationUser = null;
        UserBaseInformation userTemp = null;
        Integer userId = 0;
        // 声明变量 end

        // Update By Liwq On 2020-11-27 Start
        // Step1:开始进行校验
        // Step1.1: 基本的校验，例如手机号格式，邮箱格式校验，操作员是否存在等
        if (!CommUtils.isPhone(telephone)) {
            throw new BusinessException(ErrorMessageConstant.ECUC0019_MESSAGE, ErrorMessageConstant.ECUC0019_CODE);
        } ;

        if (StringUtils.isNotEmpty(requestObject.getEmail()) && !CommUtils.isEmail(requestObject.getEmail())) {
            throw new BusinessException(ErrorMessageConstant.ECUC0020_MESSAGE, ErrorMessageConstant.ECUC0020_CODE);
        } ;
        if (StringUtils.isNotEmpty(userPassword) && !CommUtils.checkPassword(userPassword)) {
            throw new BusinessException(ErrorMessageConstant.ECUC0021_MESSAGE, ErrorMessageConstant.ECUC0021_CODE);
        }
        /*operationUser = this.getById(operationUserId);
        if (operationUser == null) {
            throw new BusinessException(ErrorMessageConstant.ECUC0006_MESSAGE, ErrorMessageConstant.ECUC0006_CODE);
        }*/
        // Step1.2: 检查手机号，若有重复则提示：（手机号已经存在,请更改手机号）
        LambdaQueryWrapper<EmployeeInformation> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(EmployeeInformation::getChannel, channel);
        queryWrapper.eq(EmployeeInformation::getIsDelete, SystemConstant.DELETE_FLAG_0);
        queryWrapper.eq(EmployeeInformation::getTelephone, telephone);
        employees = employeeInformationMapper.selectList(queryWrapper);

        if (employees.size() > 0) {
            Set employeeName = new HashSet<String>();
            for (int i = 0; i < employees.size(); i++) {
                employeeName.add(employees.get(i).getUserName());
            }
            throw new BusinessException(ErrorMessageConstant.ECUC0024_MESSAGE + ";用户ID:" + employees.get(0).getUserId()
                + ",用户名称:" + employeeName, ErrorMessageConstant.ECUC0024_CODE);
        }
        // Step1.3: 检查工号，若工号重复则提示工号已被注册(保证工号登录)
        LambdaQueryWrapper<EmployeeInformation> queryWrapperEi = new LambdaQueryWrapper<>();
        queryWrapperEi.eq(EmployeeInformation::getChannel, channel);
        queryWrapperEi.eq(EmployeeInformation::getIsDelete, SystemConstant.DELETE_FLAG_0);
        queryWrapperEi.eq(EmployeeInformation::getEmployeeNo, employeeNo);
        employees = employeeInformationMapper.selectList(queryWrapperEi);
        if (employees.size() > 0) {
            Set employeeName = new HashSet<String>();
            for (int i = 0; i < employees.size(); i++) {
                employeeName.add(employees.get(i).getUserName());
            }
            throw new BusinessException(ErrorMessageConstant.ECUC0053_MESSAGE + ";用户ID:" + employees.get(0).getUserId()
                + ",用户名称:" + employeeName, ErrorMessageConstant.ECUC0053_CODE);
        }
        // Step1.4: 根据手机号能找到用户的话，本次添加的账号，要和之前添加的账号信息一样；
        baseInformations = commUtilsMapper.getEmployeesByPhone(telephone);
        if (baseInformations.size() > 0) {
            if (!userAccounts.equals(baseInformations.get(0).getUserAccounts())) {
                throw new BusinessException(ErrorMessageConstant.ECUC0057_MESSAGE + ";此手机号用户已经注册，用户账号为:"
                    + baseInformations.get(0).getUserAccounts(), ErrorMessageConstant.ECUC0057_CODE);
            }
            if (StringUtils.isNotEmpty(userPassword)
                && !CommUtils.getMd5SaltPassword(userPassword, baseInformations.get(0).getSalt())
                    .equals(baseInformations.get(0).getUserPassword())) {
                throw new BusinessException("请与该用户在其它渠道或组织机构/部门的密码保持一致", ErrorMessageConstant.ECUC0022_CODE);
            }
        }

        // Step2: 校验通过，将信息保存到表里
        // Step2.1: 保存到基本信息表：ur_user_base_information
        // 根据手机号能查到的话，就代表之前这个用户在别的渠道添加过，主表已经有数据，所以只往附表添加；
        // 查不到，才往主表添加
        if (baseInformations.size() == 0) {
            // 用户以前没有添加过，往主表添加数据，要校验账号不能重复；
            LambdaQueryWrapper<UserBaseInformation> q = new LambdaQueryWrapper<>();
            q.eq(UserBaseInformation::getUserAccounts, userAccounts);
            q.eq(UserBaseInformation::getIsDelete, "0");
            List<UserBaseInformation> userList = userBaseInformationMapper.selectList(q);
            if (userList.size() > 0) {
                LambdaQueryWrapper<EmployeeInformation> qwEi = new LambdaQueryWrapper<>();
                qwEi.eq(EmployeeInformation::getChannel, channel);
                qwEi.eq(EmployeeInformation::getIsDelete, SystemConstant.DELETE_FLAG_0);
                qwEi.eq(EmployeeInformation::getUserId, userList.get(0).getUserId());
                employees = employeeInformationMapper.selectList(qwEi);
                Set employeeName = new HashSet<String>();
                for (int i = 0; i < employees.size(); i++) {
                    employeeName.add(employees.get(i).getUserName());
                }
                throw new BusinessException(ErrorMessageConstant.ECUC0001_MESSAGE + ";用户ID:"
                    + userList.get(0).getUserId() + ",用户名称:" + employeeName, ErrorMessageConstant.ECUC0001_CODE);
            }
            // 用户以前没有添加过，校验员工号在所有渠道下都不能重复。
            LambdaQueryWrapper<EmployeeInformation> query = new LambdaQueryWrapper<>();
            query.eq(EmployeeInformation::getIsDelete, SystemConstant.DELETE_FLAG_0);
            query.eq(EmployeeInformation::getEmployeeNo, employeeNo);
            employees = employeeInformationMapper.selectList(query);
            if (employees.size() > 0) {
                Set employeeName = new HashSet<String>();
                for (int i = 0; i < employees.size(); i++) {
                    employeeName.add(employees.get(i).getUserName());
                }
                throw new BusinessException(ErrorMessageConstant.ECUC0053_MESSAGE + ";用户ID:"
                    + employees.get(0).getUserId() + ",用户名称:" + employeeName, ErrorMessageConstant.ECUC0053_CODE);
            }
            if (StringUtils.isBlank(userPassword)) {
                throw new BusinessException("密码不可为空", ErrorMessageConstant.ECUC0007_CODE);
            }
            UserBaseInformation userBaseInformation = dozerBeanMapper.map(requestObject, UserBaseInformation.class);
            userBaseInformation.setUserPassword(CommUtils.getMd5SaltPassword(userPassword, salt));
            userBaseInformation.setState(SystemConstant.USER_STATE_6);
            userBaseInformation.setSalt(salt);
            userBaseInformation.setUserType(SystemConstant.USER_TYPE_1);
            userBaseInformation.setCreateBy(operationUserId);
            userBaseInformation.setModifiedBy(operationUserId);
            userBaseInformation.setGmtModified(LocalDateTime.now());
            userBaseInformation.setBusinessSeqNo(requestObject.getTraceId());
            this.save(userBaseInformation);

            userId = userBaseInformation.getUserId();
        }
        // 数据已经存在，主表已经有数据了，只需要添加到附表就行了
        if (baseInformations.size() > 0) {
            userId = baseInformations.get(0).getUserId();

            // 用户以前添加过信息，这次添加可能是再别的渠道注册信息。要校验员工号别人是否用过。
            LambdaQueryWrapper<EmployeeInformation> query = new LambdaQueryWrapper<>();
            query.ne(EmployeeInformation::getUserId, userId);
            query.eq(EmployeeInformation::getIsDelete, SystemConstant.DELETE_FLAG_0);
            query.eq(EmployeeInformation::getEmployeeNo, employeeNo);
            employees = employeeInformationMapper.selectList(query);
            if (employees.size() > 0) {
                Set employeeName = new HashSet<String>();
                for (int i = 0; i < employees.size(); i++) {
                    employeeName.add(employees.get(i).getUserName());
                }
                throw new BusinessException(ErrorMessageConstant.ECUC0053_MESSAGE + ";用户ID:"
                    + employees.get(0).getUserId() + ",用户名称:" + employeeName, ErrorMessageConstant.ECUC0053_CODE);
            }
        }
        // Step2.1: 保存到员工信息附属表：ur_employee_information
        EmployeeInformation employeeInf = dozerBeanMapper.map(requestObject, EmployeeInformation.class);
        employeeInf.setCreateBy(operationUserId);
        employeeInf.setModifiedBy(operationUserId);
        employeeInf.setGmtModified(LocalDateTime.now());
        employeeInf.setUserId(userId);

        employeeInformationMapper.insert(employeeInf);
        return employeeInf.getUserId();
        // Update By Liwq On 2020-11-27 End
    }
    /* 添加港内员工事 end */

    /* 添加机构/部门 begin */
    @Transactional(rollbackFor = Exception.class)
    public Integer addOrganizationalStructure(OrganizationalStructureReq requestObject) {
        // 声明变量 begin
        Integer operationUserId = requestObject.getOperationUserId();
        String organizationalTypeDescription = getOrganizationalTypeDescription(requestObject.getOrganizationalType());
        // 父类机构id
        Integer parentId =
            requestObject.getParentId() == null ? SystemConstant.ORGANIZATIONAL_PARENT_ID : requestObject.getParentId();
        // 声明变量 end
        if (StringUtils.isNotEmpty(requestObject.getEmail()) && !CommUtils.isEmail(requestObject.getEmail())) {
            throw new BusinessException(ErrorMessageConstant.ECUC0020_MESSAGE, ErrorMessageConstant.ECUC0020_CODE);
        }
        QueryWrapper<OrganizationalStructure> queryWrapper = null;
        if (parentId != 0) {// 父类机构id不是默认值的时候需要校验是否存在
            queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("organizational_id", parentId);
            OrganizationalStructure temp = organizationalStructureMapper.selectOne(queryWrapper);
            if (temp == null) {
                throw new BusinessException(ErrorMessageConstant.ECUC0029_MESSAGE, ErrorMessageConstant.ECUC0029_CODE);
            }
        }

        queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("organizational_code", requestObject.getOrganizationalCode());
        queryWrapper.eq("channel", requestObject.getChannel());
        Integer integer = organizationalStructureMapper.selectCount(queryWrapper);
        if (integer != null && integer > 0) {
            throw new BusinessException(ErrorMessageConstant.ECUC0030_MESSAGE, ErrorMessageConstant.ECUC0030_CODE);
        }

        //
        queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id", parentId);
        queryWrapper.eq("organizational_name", requestObject.getOrganizationalName());
        queryWrapper.eq("organizational_type", requestObject.getOrganizationalType());
        queryWrapper.eq("channel", requestObject.getChannel());
        OrganizationalStructure temp = organizationalStructureMapper.selectOne(queryWrapper);
        if (temp != null) {
            throw new BusinessException(
                organizationalTypeDescription + ":" + requestObject.getOrganizationalName() + "已经存在",
                ErrorMessageConstant.ECUC0002_CODE);
        }
        OrganizationalStructure organizationalStructure =
            dozerBeanMapper.map(requestObject, OrganizationalStructure.class);
        UserBaseInformation userBaseInformation = new UserBaseInformation();
        if (SystemConstant.ORGANIZATIONAL_STRUCTURE_TYPE_0.equals(requestObject.getOrganizationalType())) {
            userBaseInformation.setUserType(SystemConstant.USER_TYPE_4);
        } else if (SystemConstant.ORGANIZATIONAL_STRUCTURE_TYPE_1.equals(requestObject.getOrganizationalType())) {
            userBaseInformation.setUserType(SystemConstant.USER_TYPE_5);
        }else{
            throw new BusinessException(ErrorMessageConstant.ECUC0066_MESSAGE, ErrorMessageConstant.ECUC0066_CODE);
        }
        userBaseInformation.setBusinessSeqNo(requestObject.getTraceId());
        userBaseInformation.setChannel(requestObject.getChannel());
        userBaseInformation.setGmtCreate(LocalDateTime.now());
        userBaseInformation.setCreateBy(operationUserId);
        userBaseInformation.setGmtModified(LocalDateTime.now());
        userBaseInformation.setModifiedBy(operationUserId);
        // MD5加密的生活用的盐
        String salt = CommUtils.getSalt();
        // 生成随机数
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        String userAccounts = uuid.substring(0, 20);
        String userPassword = uuid;
        userBaseInformation.setUserAccounts(userAccounts);
        userBaseInformation.setUserPassword(userPassword);
        userBaseInformation.setSalt(salt);
        userBaseInformationMapper.insert(userBaseInformation);
        organizationalStructure.setBusinessSeqNo(requestObject.getTraceId());
        organizationalStructure.setCreateBy(operationUserId);
        organizationalStructure.setModifiedBy(operationUserId);
        organizationalStructure.setGmtModified(LocalDateTime.now());
        organizationalStructure.setParentId(parentId);
        organizationalStructure.setOrganizationalId(userBaseInformation.getUserId());
        organizationalStructureMapper.insert(organizationalStructure);
        return organizationalStructure.getOrganizationalId();
    }
    /* 添加机构/部门 end */

    /**
     * 港内组织机构/部门查询（带组织员工数量）
     *
     * @param requestObject
     * @return
     */
    public List<OrganizationalStructureWithCountsDto>
        queryOrganizationalStructureInfoWithCounts(QueryOrganizationalStructureReq requestObject) {
        List<OrganizationalStructureWithCountsDto> results = new ArrayList<>();
        // 先调用“港内组织机构/部门查询”接口，查询不带人数的数据，然后再循环处理；
        List<OrganizationalStructureDto> queryOrganizationalStructureInfo =
            queryOrganizationalStructureInfo(requestObject);
        if (queryOrganizationalStructureInfo != null && queryOrganizationalStructureInfo.size() > 0) {
            for (OrganizationalStructureDto obj : queryOrganizationalStructureInfo) {
                OrganizationalStructureWithCountsDto o =
                    dozerBeanMapper.map(obj, OrganizationalStructureWithCountsDto.class);
                // 将数量字段补上
                LinkedHashMap<Integer, String> subs = new LinkedHashMap<>();
                List<Integer> ids = new ArrayList<>(10);
                ids.add(Integer.parseInt(obj.getOrganizationalId()));
                roleManagementModel.getSubOrganizationalId(ids, subs);
                List<Integer> idList = new ArrayList<>(subs.keySet());
                idList.add(Integer.parseInt(obj.getOrganizationalId()));

                LambdaQueryWrapper<EmployeeInformation> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(EmployeeInformation::getIsDelete, 0);
                queryWrapper.eq(EmployeeInformation::getChannel, obj.getChannel());
                queryWrapper.in(EmployeeInformation::getOrganizationalId, idList);
                Integer counts = employeeInformationMapper.selectCount(queryWrapper);
                o.setMemberCounts(counts);
                results.add(o);
            }
        }
        return results;
    }

    /* 查询机构/部门 begin */
    /*2021-08-09 syf 当渠道为产融核心和山港易付时只能通过queryChannel字段实现跨渠道查询*/
    public List<OrganizationalStructureDto>
        queryOrganizationalStructureInfo(QueryOrganizationalStructureReq requestObject) {
        // 声明变量 begin
        String sortField = requestObject.getSortField();
        String sortOrder = requestObject.getSortOrder();
        List<OrganizationalStructureDto> records = new ArrayList<>();
        PagerInfo pagerInfo = requestObject.getPagerInfo();
        Page<OrganizationalStructure> organizationalStructurePage =
            new Page<>(pagerInfo.getPageNum(), pagerInfo.getPageSize());
        // 声明变量 end
        QueryWrapper<OrganizationalStructure> queryWrapper = new QueryWrapper<>();
        if(StringUtils.isNotBlank(requestObject.getAllChild())){
            if(!("0".equals(requestObject.getAllChild())||"1".equals(requestObject.getAllChild()))){
                throw new BusinessException(ErrorMessageConstant.ECUC0069_MESSAGE, ErrorMessageConstant.ECUC0069_CODE);
            }
        }
        if (requestObject.getParentId() != null) {
            //2022-09-13 syf新增可查询所有子级,1为查询所有子级
            if("1".equals(requestObject.getAllChild())&&requestObject.getOrganizationalId() == null) {
                LinkedHashMap<Integer, String> subs = new LinkedHashMap<>();
                List<Integer> ids = new ArrayList<>();
                ids.add(requestObject.getParentId());
                roleManagementModel.getSubOrganizationalId(ids, subs);
                List<Integer> idList = new ArrayList<>(subs.keySet());
                if(idList.size()>0) {
                    queryWrapper.in("organizational_id", idList);
                }else{
                    queryWrapper.eq("parent_id", requestObject.getParentId());
                }
            }else{
                queryWrapper.eq("parent_id", requestObject.getParentId());
            }
        }
        if (requestObject.getOrganizationalName() != null) {
            queryWrapper.like("organizational_name", requestObject.getOrganizationalName());
        }
        if (requestObject.getOrganizationalCode() != null) {
            queryWrapper.like("organizational_code", requestObject.getOrganizationalCode());
        }

        if (requestObject.getOrganizationalType() != null) {
            queryWrapper.like("organizational_type", requestObject.getOrganizationalType());
        }
        if (requestObject.getOrganizationalId() != null) {
            queryWrapper.eq("organizational_id", requestObject.getOrganizationalId());
        }
        if (requestObject.getSgyfId() != null) {
            queryWrapper.eq("sgyf_id", requestObject.getSgyfId());
        }

        // Update By Liwq On 2020-11-03 Start
        // 允许传多个查询渠道过来，用英文逗号隔开。例：C01,C02
        if ("C01".equals(requestObject.getChannel()) || "C02".equals(requestObject.getChannel())
            || "C06".equals(requestObject.getChannel()) || "C03".equals(requestObject.getChannel())
                || "C08".equals(requestObject.getChannel())|| "C10".equals(requestObject.getChannel())) {
            if (StringUtils.isNotBlank(requestObject.getQueryChannel())) {
                // queryWrapper.like("channel", requestObject.getQueryChannel());
                List<String> queryChannelList =
                    Arrays.asList(requestObject.getQueryChannel().split(queryChannelSplitFlag));
                queryWrapper.in("channel", queryChannelList);
            }
        }
        // Update By Liwq On 2020-11-03 End

        // 2020-10-19 应渠道要求添加flag查询条件 songyf
        if (requestObject.getFlag() != null) {
            queryWrapper.eq("flag", requestObject.getFlag());
        }
        // 2021-01-26 支持自定义排序查询 songyf
        if (StringUtils.isNotEmpty(sortField) && StringUtils.isNotEmpty(sortOrder)) {
            if ("createTime".equals(sortField)) {
                if ("asc".equals(sortOrder)) {
                    queryWrapper.orderByAsc("gmt_create");
                } else if ("desc".equals(sortOrder)) {
                    queryWrapper.orderByDesc("gmt_create");
                }
            } else if ("orgCode".equals(sortField)) {
                if ("asc".equals(sortOrder)) {
                    queryWrapper.orderByAsc("organizational_code");
                } else if ("desc".equals(sortOrder)) {
                    queryWrapper.orderByDesc("organizational_code");
                }
            } else if ("orgName".equals(sortField)) {
                if ("asc".equals(sortOrder)) {
                    queryWrapper.orderByAsc("organizational_name");
                } else if ("desc".equals(sortOrder)) {
                    queryWrapper.orderByDesc("organizational_name");
                }
            } else if ("parentId".equals(sortField)) {
                if ("asc".equals(sortOrder)) {
                    queryWrapper.orderByAsc("parent_id");
                } else if ("desc".equals(sortOrder)) {
                    queryWrapper.orderByDesc("parent_id");
                }
            }
        } else if (StringUtils.isEmpty(sortField) && StringUtils.isEmpty(sortOrder)) {
        } else {
            throw new BusinessException(ErrorMessageConstant.ECUC0059_MESSAGE, ErrorMessageConstant.ECUC0059_CODE);
        }
        IPage<OrganizationalStructure> page =
            organizationalStructureMapper.selectPage(organizationalStructurePage, queryWrapper);
        List<OrganizationalStructure> organizationalStructureList = page.getRecords();
        //2022-09-14
        for (OrganizationalStructure obj : organizationalStructureList) {
            OrganizationalStructureDto organSD = dozerBeanMapper.map(obj, OrganizationalStructureDto.class);
            OrganizationalStructure temp = selectFormatIdByOrganizational(obj);
            if(temp!=null) {
                organSD.setFormatId(temp.getOrganizationalId());
            }
            records.add(organSD);
        }
        pagerInfo.setTotal(page.getTotal());
        return records;
    }
    /* 查询机构/部门 end */

    /* 修改机构/ 部门 begin */
    @Transactional(rollbackFor = Exception.class)
    public String modifyOrganizationalStructureReq(ModifyOrganizationalStructureReq requestObject) {
        // 声明变量 begin
        String returnsResult = SystemConstant.SYSTEM_SUCCESS;
        Integer organizationalId = null;
        String organizationalName = requestObject.getOrganizationalName();
        String channel = requestObject.getChannel();
        QueryWrapper<OrganizationalStructure> queryWrapper = new QueryWrapper<>();
        // 声明变量 end
        organizationalId = requestObject.getOrganizationalId();
        queryWrapper.eq("organizational_id", organizationalId);
        OrganizationalStructure organizationalStructure = organizationalStructureMapper.selectOne(queryWrapper);

        if (organizationalStructure == null) {
            throw new BusinessException(ErrorMessageConstant.ECUC0031_MESSAGE, ErrorMessageConstant.ECUC0031_CODE);
        }

        QueryWrapper<OrganizationalRoleRelation> queryWrapperOrr = new QueryWrapper<>();
        queryWrapperOrr.eq("organizational_id", organizationalId);
        // 渠道端要求去掉该部分限制 宋一帆 2020-10-10
        // List<OrganizationalRoleRelation> organizationalRoleRelations =
        // organizationalRoleRelationMapper.selectList(queryWrapperOrr);
        // if (organizationalRoleRelations.size() > 0) {
        // throw new BusinessException("机构/部门" + organizationalId + "存在机构部门关联，不能修改",
        // ErrorMessageConstant.ECUC0030_CODE);
        // }

        if (StringUtils.isNotEmpty(organizationalName)) {
            queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("parent_id", organizationalStructure.getParentId());
            queryWrapper.eq("organizational_name", requestObject.getOrganizationalName());
            queryWrapper.eq("organizational_type", organizationalStructure.getOrganizationalType());
            queryWrapper.eq("channel", organizationalStructure.getChannel());

            OrganizationalStructure temp = organizationalStructureMapper.selectOne(queryWrapper);
            if (temp != null && !organizationalId.equals(temp.getOrganizationalId())) {
                throw new BusinessException("(机构/部门)已经存在", ErrorMessageConstant.ECUC0030_CODE);
            }
        }

        Integer tempOrganizationalId = organizationalStructure.getOrganizationalId();
        String tempChannel = organizationalStructure.getChannel();
        OrganizationalStructureHistory organizationalStructureHistory =
            dozerBeanMapper.map(organizationalStructure, OrganizationalStructureHistory.class);
        organizationalStructureHistory.setOperationType(SystemConstant.ORGAN_OPERATION_TYPE_0);
        organizationalStructureHistory.setGmtCreate(LocalDateTime.now());
        organizationalStructureHistory.setCreateBy(requestObject.getOperationUserId());
        organizationalStructureHistory.setGmtModified(LocalDateTime.now());
        organizationalStructureHistory.setModifiedBy(requestObject.getOperationUserId());
        organizationalStructureHistoryMapper.insert(organizationalStructureHistory);
        dozerBeanMapper.map(requestObject, organizationalStructure);
        organizationalStructure.setChannel(tempChannel);
        organizationalStructure.setOrganizationalId(tempOrganizationalId);
        organizationalStructure.setGmtModified(LocalDateTime.now());
        organizationalStructure.setModifiedBy(organizationalId);
        organizationalStructureMapper.updateById(organizationalStructure);
        return returnsResult;
    }
    /* 修改机构/ 部门 end */

    /*  删除机构/部门 begin */
    @Transactional(rollbackFor = Exception.class)
    public String deleteOrganizationalStructure(DeleteOrganizationalStructureReq requestObject) {
        // 声明变量 begin
        String returnsResult = SystemConstant.SYSTEM_SUCCESS;
        // 删除机构条件，机构/部门下没有子集机构/部门，机构/部门下没有角色对应关系（查询关系表）。
        Integer organizationalId = requestObject.getOrganizationalId();
        QueryWrapper<OrganizationalStructure> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("organizational_id", organizationalId);
        OrganizationalStructure organizationalStructure = organizationalStructureMapper.selectById(organizationalId);
        if (organizationalStructure == null) {
            throw new BusinessException("机构/部门不存在");
        }
        queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id", organizationalId);
        List<OrganizationalStructure> organizationalStructures = organizationalStructureMapper.selectList(queryWrapper);
        if (organizationalStructures.size() > 0) {
            throw new BusinessException("机构/部门(" + organizationalStructures.get(0).getOrganizationalName() + ",id:"
                    + organizationalId + ")存在子集，请先删除", ErrorMessageConstant.ECUC0030_CODE);
        }
        QueryWrapper<OrganizationalRoleRelation> queryWrapperRelation = new QueryWrapper<>();
        queryWrapperRelation.eq("organizational_id", organizationalId);
        Integer integer = organizationalRoleRelationMapper.selectCount(queryWrapperRelation);
        if (integer > 0) {
            queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("organizational_id", organizationalId);
            List<OrganizationalStructure> orgs = organizationalStructureMapper.selectList(queryWrapper);
            throw new BusinessException(
                    "机构/部门(" + orgs.get(0).getOrganizationalName() + ",id:" + organizationalId + ")存在角色对应关系，请先删除",
                    ErrorMessageConstant.ECUC0030_CODE);
        }
        //2022-09-13syf增加业态判断
        if (requestObject.getFormatId()!=null){
//            if (!SystemConstant.ORGANIZATIONAL_PARENT_ID.equals(organizationalStructure.getParentId())) {
                OrganizationalStructure organ = organizationalStructure;
                organ = selectFormatIdByOrganizational(organ);
                if (organ != null) {
//                    if (SystemConstant.ORGANIZATIONAL_STRUCTURE_TYPE_0.equals(organ.getOrganizationalType())) {
                        if (!organ.getOrganizationalId().equals(requestObject.getFormatId())) {
                            throw new BusinessException(ErrorMessageConstant.ECUC0067_MESSAGE, ErrorMessageConstant.ECUC0067_CODE);
                        }
//                    }
                }
//            }
    }
        //2022-09-13增加业态判断end
        // 声明变量 end
        OrganizationalStructureHistory organizationalStructureHistory =
            dozerBeanMapper.map(organizationalStructure, OrganizationalStructureHistory.class);
        organizationalStructureHistory.setOperationType(SystemConstant.ORGAN_OPERATION_TYPE_1);
        organizationalStructureHistory.setGmtCreate(LocalDateTime.now());
        organizationalStructureHistory.setCreateBy(requestObject.getOperationUserId());
        organizationalStructureHistory.setGmtModified(LocalDateTime.now());
        organizationalStructureHistory.setModifiedBy(requestObject.getOperationUserId());
        organizationalStructureHistoryMapper.insert(organizationalStructureHistory);
        userBaseInformationMapper.deleteById(organizationalId);
        organizationalStructureMapper.deleteById(organizationalId);
        return returnsResult;
    }
    /* 删除机构/部门 end */

    /* 查询人员 begin */
    public List<EmployeeInfoDto> queryEmployee(QueryEmployeesInfoReq requestObject) {
        // 声明变量 begin
        List<EmployeeInformation> records = null;
        List<EmployeeInfoDto> employeeInfoDtoList = new ArrayList<>();
        String channel = requestObject.getChannel();
        List<Map<String, Object>> resultTemp = null;
        Integer organizationalId = requestObject.getOrganizationalId();
        PagerInfo pagerInfo = requestObject.getPagerInfo();
        // 当前页，总条数 构造 page 对象
        Page<EmployeeInformation> page = new Page<>(pagerInfo.getPageNum(), pagerInfo.getPageSize());
        // 声明变量 end

        // Update By Liwq On 2020-11-27 Start
        // Step1: 查询员工基本信息
        // Step1.1：准备查询条件
        Map<String, Object> objectObjectMap = new HashMap<>();
        if (requestObject.getUserId() != null) {
            objectObjectMap.put("userId", requestObject.getUserId());
        }
        if (StringUtils.isNotEmpty(requestObject.getUserName())) {
            objectObjectMap.put("userName", requestObject.getUserName());
        }
        if (StringUtils.isNotEmpty(requestObject.getFlag())) {
            objectObjectMap.put("flag", requestObject.getFlag());
        }
        if (requestObject.getOrganizationalId() != null) {
            // update by liwq on 2021-09-03 start
            // 标记是1，不仅查询该组织，也要查询子组织
            LinkedHashMap<Integer, String> subs = new LinkedHashMap<>();
            if (requestObject.getQuerySubOrgFlag() == 1) {
                List<Integer> ids = new ArrayList<>(10);
                ids.add(requestObject.getOrganizationalId());
                roleManagementModel.getSubOrganizationalId(ids, subs);
            }
            // 标记是0，只查该组织
            List<Integer> idList = new ArrayList<>(subs.keySet());
            idList.add(requestObject.getOrganizationalId());
            // objectObjectMap.put("organizationalId", requestObject.getOrganizationalId());
            objectObjectMap.put("organizationalId", idList);
            // update by liwq on 2021-09-03 end
        }
        if (StringUtils.isNotEmpty(requestObject.getTelephone())) {
            objectObjectMap.put("telephone", requestObject.getTelephone());
        }
        if (StringUtils.isNotEmpty(requestObject.getEmployeeNo())) {
            objectObjectMap.put("employeeNo", requestObject.getEmployeeNo());
        }
        if (StringUtils.isNotEmpty(requestObject.getRoleName())) {
            objectObjectMap.put("roleName", requestObject.getRoleName());
        }
        if (requestObject.getRoleId() != null) {
            objectObjectMap.put("roleId", requestObject.getRoleId());
        }
        if (StringUtils.isNotEmpty(requestObject.getCreateTimeStart())) {
            Boolean flag = CommUtils.validDateStr(requestObject.getCreateTimeStart(), null);
            if (!flag) {
                throw new BusinessException("创建开始日期格式不正确", ErrorMessageConstant.ECUC0030_CODE);
            }
            objectObjectMap.put("createTimeStart", requestObject.getCreateTimeStart());
        }
        if (StringUtils.isNotEmpty(requestObject.getCreateTimeEnd())) {
            Boolean flag = CommUtils.validDateStr(requestObject.getCreateTimeEnd(), null);
            if (!flag) {
                throw new BusinessException("创建结束日期格式不正确", ErrorMessageConstant.ECUC0030_CODE);
            }
            objectObjectMap.put("createTimeEnd", requestObject.getCreateTimeEnd() + " 23:59:59");
        }
        if (StringUtils.isNotEmpty(requestObject.getPapersType())) {
            objectObjectMap.put("papers_type", requestObject.getPapersType());
        }
        if (StringUtils.isNotEmpty(requestObject.getPapersNo())) {
            objectObjectMap.put("papers_no", requestObject.getPapersNo());
        }
        // 支持传多个渠道，以英文逗号隔开，例：C01,C02
        List<String> queryChannelList = new ArrayList<>();
        if (StringUtils.isNotEmpty(requestObject.getQueryChannel())) {
            queryChannelList = Arrays.asList(requestObject.getQueryChannel().split(queryChannelSplitFlag));
        } else {
            queryChannelList.add(requestObject.getChannel());
        }
        objectObjectMap.put("channel", queryChannelList);

        // Step1.2：进行查询
        records = commUtilsMapper.getEmployeeInfo(page, objectObjectMap);

        // Step2：对员工数据遍历整理，补充员工角色等信息
        records.forEach(obj -> {
            List<InPortRoleDto> listIpr = new ArrayList<>();

            // update by liwq on 2021-09-06 start;改成用一个SQL语句;
            // Step2.1 从组织角色关系表里，找出这个员工，所在渠道，所在组织的所有的 角色关系
            // QueryWrapper<OrganizationalRoleRelation> parameter = new QueryWrapper<>();
            // parameter.eq("user_id", obj.getUserId());
            // parameter.eq("channel", obj.getChannel());
            // parameter.eq("organizational_id", obj.getOrganizationalId());
            // List<OrganizationalRoleRelation> temp = organizationalRoleRelationMapper.selectList(parameter);
            // // Step2.2 遍历角色关系，获取角色信息，添加给员工
            // temp.forEach(tempObj -> {
            // QueryWrapper<InPortRole> parameterIpr = new QueryWrapper<>();
            // parameterIpr.eq("role_id", tempObj.getRoleId());
            // InPortRole inPortRole = inPortRoleMapper.selectOne(parameterIpr);
            // InPortRoleDto inPortRoleDto = new InPortRoleDto();
            // dozerBeanMapper.map(inPortRole, inPortRoleDto);
            // listIpr.add(inPortRoleDto);
            // });

            Map<String, Object> map = new HashMap<>();
            map.put("userId", obj.getUserId());
            map.put("channel", obj.getChannel());
            map.put("organizationalId", obj.getOrganizationalId());
            listIpr = commUtilsMapper.getRloeInfos(map);
            // update by liwq on 2021-09-06 end;改成用一个SQL语句;

            // Step2.3 整理Response对象；
            // 把刚才从数据库查出来的员工信息，映射成DTO response 对象；然后缺少什么字段，再挨个补缺；
            EmployeeInfoDto employeeInfoDto = new EmployeeInfoDto();
            dozerBeanMapper.map(obj, employeeInfoDto);
            employeeInfoDto.setInPortRoleDto(listIpr);
            UserBaseInformation userBaseInformation = userBaseInformationMapper.selectById(obj.getUserId());
            if (userBaseInformation != null) {
                employeeInfoDto.setUserAccounts(userBaseInformation.getUserAccounts());
            }
            //2022-09-15 新增查询员工所属业态
            if(employeeInfoDto.getOrganizationalId()!=null) {
                OrganizationalStructure temp = new OrganizationalStructure();
                LambdaQueryWrapper<OrganizationalStructure> queryParent = new LambdaQueryWrapper();
                queryParent.eq(OrganizationalStructure::getOrganizationalId, employeeInfoDto.getOrganizationalId());
                queryParent.orderByDesc(OrganizationalStructure::getGmtModified);
                List<OrganizationalStructure> orglists = organizationalStructureMapper.selectList(queryParent);
                if (orglists.size() > 0) {
                    temp = orglists.get(0);
                }
                if (temp != null) {
                    temp = selectFormatIdByOrganizational(temp);
                }
                if (temp != null) {
                    employeeInfoDto.setFormatId(temp.getOrganizationalId());
                }
            }
            employeeInfoDtoList.add(employeeInfoDto);
        });
        pagerInfo.setTotal(page.getTotal());
        return employeeInfoDtoList;
        // Update By Liwq On 2020-11-27 End
    }
    /* 查询人员 end */

    /* 修改港内员工信息 begin */
    @Transactional(rollbackFor = Exception.class)
    public String changeEmployeesInfo(ChangeEmployeesInfoReq requestObject) {
        // 声明变量 begin
        Integer userId = requestObject.getUserId();
        String telephone = requestObject.getTelephone();
        String userName = requestObject.getUserName();
        Integer organizationalId = null;
        if (requestObject.getOrganizationalId() != null) {
            organizationalId = requestObject.getOrganizationalId();
        }
        String channel = requestObject.getChannel();
        List<EmployeeInformation> employeeInformations = new ArrayList<>();
        // 声明变量 end

        // Step1: 校验
        // Step1.1: 校验这个手机号别的用户是否已经在用
        if (StringUtils.isNotEmpty(telephone)) {
            LambdaQueryWrapper<EmployeeInformation> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.ne(EmployeeInformation::getUserId, userId);
            queryWrapper.eq(EmployeeInformation::getIsDelete, SystemConstant.DELETE_FLAG_0);
            queryWrapper.eq(EmployeeInformation::getTelephone, telephone);
            employeeInformations = employeeInformationMapper.selectList(queryWrapper);
            if (0 != employeeInformations.size()) {
                Set employeeName = new HashSet<String>();
                for (int i = 0; i < employeeInformations.size(); i++) {
                    employeeName.add(employeeInformations.get(i).getUserName());
                }
                throw new BusinessException(ErrorMessageConstant.ECUC0024_MESSAGE + ";用户ID:"
                    + employeeInformations.get(0).getUserId() + ",用户名称:" + employeeName,
                    ErrorMessageConstant.ECUC0024_CODE);
            }
        }

        // Step2: 从数据库查出要修改的 港内员工信息，包括基本信息和附表的信息。
        // Step2.1: 附表信息。
        // userId + organizationalId + channel + isDelete,确定唯一一条可用数据。
        LambdaQueryWrapper<EmployeeInformation> parameterEi = new LambdaQueryWrapper<>();
        parameterEi.eq(EmployeeInformation::getUserId, userId);
        if (organizationalId != null) {
            parameterEi.eq(EmployeeInformation::getOrganizationalId, organizationalId);
        }
        parameterEi.eq(EmployeeInformation::getIsDelete, SystemConstant.DELETE_FLAG_0);
        parameterEi.eq(EmployeeInformation::getChannel, channel);
        Integer count = employeeInformationMapper.selectCount(parameterEi);
        if (count > 1) {
            throw new BusinessException("请输入用户所属组织机构organizationalId", ErrorMessageConstant.ECUC0002_CODE);
        }
        EmployeeInformation employeeInformation = employeeInformationMapper.selectOne(parameterEi);
        if (employeeInformation == null) {
            throw new BusinessException("用户：" + userId + ",在当前渠道不存在", ErrorMessageConstant.ECUC0001_CODE);
        }
        // Step2.2: 基本信息。
        LambdaQueryWrapper<UserBaseInformation> parameterUbi = new LambdaQueryWrapper<>();
        parameterUbi.eq(UserBaseInformation::getUserId, userId);
        UserBaseInformation userBaseInformation = this.getOne(parameterUbi);

        // Step3: 开始修改数据；包括：新增到历史数据表 & 修改现有数据。
        // ur_user_base_information_history表 及 ur_user_base_information表
        Integer userHistoryId = generalService.insertUserBaseInformationHistory(userBaseInformation);
        String tempChannel = userBaseInformation.getChannel(); // 为了解决原始渠道被覆盖问题
        dozerBeanMapper.map(requestObject, userBaseInformation);
        userBaseInformation.setChannel(tempChannel);
        userBaseInformation.setGmtModified(LocalDateTime.now());
        userBaseInformation.setModifiedBy(requestObject.getOperationUserId());
        this.updateById(userBaseInformation);

        // ur_employee_information_history表 及 ur_employee_information表
        generalService.insertEmployeeInformationHistory(employeeInformation, userHistoryId);
        dozerBeanMapper.map(requestObject, employeeInformation);
        employeeInformation.setGmtModified(LocalDateTime.now());
        employeeInformation.setModifiedBy(requestObject.getOperationUserId());
        employeeInformationMapper.updateById(employeeInformation);
        return SystemConstant.SYSTEM_SUCCESS;
    }
    /* 修改港内员工信息 end */

    private String getOrganizationalTypeDescription(String type) {
        // 机构类型:0-机构,1-部门'
        return type.equals(SystemConstant.ORGANIZATIONAL_STRUCTURE_TYPE_0) ? "机构" : "部门";
    }

    /**
     * @param requestObject
     * @return
     */
    public List<DingTalkSearchOrgRelationDTO> queryDingTalkEmployee(QueryDingTalkEmployeesInfoReq requestObject) {
        List<DingTalkSearchOrgRelationDTO> returnLists = new ArrayList<DingTalkSearchOrgRelationDTO>();
        // 获取组织机构
        LambdaQueryWrapper<OrganizationalStructure> queryOS = new LambdaQueryWrapper<OrganizationalStructure>();
        if (StringUtils.isNotBlank(requestObject.getQueryChannel())) {
            List<String> queryChannelList = Arrays.asList(requestObject.getQueryChannel().split(queryChannelSplitFlag));
            queryOS.in(OrganizationalStructure::getChannel, queryChannelList);
        }
        if (requestObject.getOrganizationalId() != null) {
            queryOS.eq(OrganizationalStructure::getOrganizationalId, requestObject.getOrganizationalId());
        }
        List<OrganizationalStructure> organizationalStructures = organizationalStructureMapper.selectList(queryOS);
        List<DingTalkSearchOrgRelationDTO> dingTalkSearchOrgRelationDTOs =
            BeanUtil.mapList(dozerBeanMapper, organizationalStructures, DingTalkSearchOrgRelationDTO.class);
        // List<String> orgidList = null;
        // for(int i=0;i<dingTalkSearchOrgRelationDTOs.size();i++) {
        // orgidList.add(dingTalkSearchOrgRelationDTOs.get(0).getOrganizationalId());
        // }
        // 获取角色
        LambdaQueryWrapper<InPortRole> queryIPR = new LambdaQueryWrapper<InPortRole>();
        if (requestObject.getRoleId() != null) {
            queryIPR.eq(InPortRole::getRoleId, requestObject.getRoleId());
        }
        List<InPortRole> inPortRoles = inPortRoleMapper.selectList(queryIPR);
        List<DingTalkSearchInPortRoleDto> inPortRoleDtos =
            BeanUtil.mapList(dozerBeanMapper, inPortRoles, DingTalkSearchInPortRoleDto.class);
        // 获取员工
        LambdaQueryWrapper<EmployeeInformation> queryEI = new LambdaQueryWrapper<EmployeeInformation>();
        List<EmployeeInformation> employeeInformations = employeeInformationMapper.selectList(queryEI);
        List<DingTalkSearchEmployeeInfoDto> employeeInfoDtos =
            BeanUtil.mapList(dozerBeanMapper, employeeInformations, DingTalkSearchEmployeeInfoDto.class);
        // 获取关系
        LambdaQueryWrapper<OrganizationalRoleRelation> queryORR = new LambdaQueryWrapper<OrganizationalRoleRelation>();
        List<OrganizationalRoleRelation> organizationalRoleRelations =
            organizationalRoleRelationMapper.selectList(queryORR);
        List<OrganizationalRoleRelation> tempLists = organizationalRoleRelations;
        for (int i = 0; i < dingTalkSearchOrgRelationDTOs.size(); i++) {
            List<DingTalkSearchInPortRoleDto> dingTalkSearchInPortRoleDtos = new ArrayList<>();
            for (int j = 0; j < organizationalRoleRelations.size(); j++) {
                if (dingTalkSearchOrgRelationDTOs.get(i).getOrganizationalId()
                    .equals(organizationalRoleRelations.get(j).getOrganizationalId())) {
                    for (int k = 0; k < inPortRoleDtos.size(); k++) {
                        List<DingTalkSearchEmployeeInfoDto> dingTalkSearchEmployeeInfoDtos =
                            new ArrayList<DingTalkSearchEmployeeInfoDto>();
                        if (inPortRoleDtos.get(k).getRoleId().equals(organizationalRoleRelations.get(j).getRoleId())) {
                            for (int t = 0; t < tempLists.size(); t++) {
                                if (tempLists.get(t).getOrganizationalId()
                                    .equals(dingTalkSearchOrgRelationDTOs.get(i).getOrganizationalId())
                                    && tempLists.get(t).getRoleId().equals(inPortRoleDtos.get(k).getRoleId())) {
                                    for (int p = 0; p < employeeInfoDtos.size(); p++) {
                                        if (employeeInfoDtos.get(p).getUserId().equals(tempLists.get(t).getUserId())) {
                                            dingTalkSearchEmployeeInfoDtos.add(employeeInfoDtos.get(p));
                                        }
                                    }
                                }
                            }
                            // DingTalkSearchInPortRoleDto dingTalkSearchInPortRoleDto = inPortRoleDtos.get(k);
                            DingTalkSearchInPortRoleDto dingTalkSearchInPortRoleDto = new DingTalkSearchInPortRoleDto();
                            dingTalkSearchInPortRoleDto.setChannel(inPortRoleDtos.get(k).getChannel());
                            dingTalkSearchInPortRoleDto.setDescribeStr(inPortRoleDtos.get(k).getDescribeStr());
                            dingTalkSearchInPortRoleDto.setRoleId(inPortRoleDtos.get(k).getRoleId());
                            dingTalkSearchInPortRoleDto.setRoleName(inPortRoleDtos.get(k).getRoleName());
                            List<DingTalkSearchEmployeeInfoDto> tempEmployees =
                                new ArrayList<DingTalkSearchEmployeeInfoDto>();
                            tempEmployees = dingTalkSearchEmployeeInfoDtos;
                            dingTalkSearchInPortRoleDto.setEmployeeInfoDto(tempEmployees);
                            if (!dingTalkSearchInPortRoleDtos.contains(dingTalkSearchInPortRoleDto)) {
                                dingTalkSearchInPortRoleDtos.add(dingTalkSearchInPortRoleDto);
                            }
                        }
                    }
                }
            }
            dingTalkSearchOrgRelationDTOs.get(i).setInPortRoleList(dingTalkSearchInPortRoleDtos);
            returnLists.add(dingTalkSearchOrgRelationDTOs.get(i));
        }
        return returnLists;
    }

    /**
     * @param requestObj
     * @return
     */
    public List<OrganizationalListInfoDto> pursuantTelephoneGetUserName(TelephoneGetUserNameReq requestObj) {

        // 声明变量 begin
        String telephone = requestObj.getTelephone();
        String userAccounts = requestObj.getUserAccounts();
        if (StringUtils.isBlank(telephone) && StringUtils.isBlank(userAccounts)) {
            throw new BusinessException(ErrorMessageConstant.ECUC0061_MESSAGE, ErrorMessageConstant.ECUC0019_CODE);
        }
        if (StringUtils.isNotBlank(telephone) && !CommUtils.isPhone(telephone)) {
            throw new BusinessException(ErrorMessageConstant.ECUC0019_MESSAGE, ErrorMessageConstant.ECUC0019_CODE);
        }
        String channel = requestObj.getChannel();
        List<OrganizationalListInfoDto> organizationals =
            enterpriseUserInfoMapper.pursuantTelephoneGetEmployeeName(telephone, userAccounts, channel);
        List<OrganizationalListInfoDto> organizationalList = new ArrayList<OrganizationalListInfoDto>();
        for (int i = 0; i < organizationals.size(); i++) {
            OrganizationalStructure org = new OrganizationalStructure();
            if (SystemConstant.ORGANIZATIONAL_STRUCTURE_TYPE_1.equals(organizationals.get(i).getOrganizationalType())) {
                LambdaQueryWrapper<OrganizationalStructure> query = new LambdaQueryWrapper<OrganizationalStructure>();
                query.eq(OrganizationalStructure::getOrganizationalId, organizationals.get(i).getOrganizationalId());
                org = organizationalStructureMapper.selectOne(query);
                while (SystemConstant.ORGANIZATIONAL_STRUCTURE_TYPE_1.equals(org.getOrganizationalType())) {
                    query = new LambdaQueryWrapper<OrganizationalStructure>();
                    query.eq(OrganizationalStructure::getOrganizationalId, org.getParentId());
                    org = organizationalStructureMapper.selectOne(query);
                }
                OrganizationalListInfoDto organizational = new OrganizationalListInfoDto();
                dozerBeanMapper.map(org, organizational);
                boolean temp = true;
                for (int j = 0; j < organizationalList.size(); j++) {
                    if (organizationalList.get(j).getOrganizationalId().equals(organizational.getOrganizationalId())) {
                        temp = false;
                    }
                }
                if (temp) {
                    organizationalList.add(organizational);
                }
            } else {
                organizationalList.add(organizationals.get(i));
            }
        }
        return organizationalList;

    }
    //2022-09-14 查询组织机构所属最上级
    public OrganizationalStructure selectFormatIdByOrganizational(OrganizationalStructure organ){
//        SystemConstant.ORGANIZATIONAL_STRUCTURE_TYPE_2.equals(organ.getOrganizationalType())||
        if(organ.getOrganizationalId()!=null) {
            int a = 0;
            while (!(SystemConstant.ORGANIZATIONAL_PARENT_ID.equals(organ.getParentId()) || organ.getOrganizationalId().equals(organ.getParentId()) || organ.getParentId() == null) && a < 50) {
                LambdaQueryWrapper<OrganizationalStructure> queryParent = new LambdaQueryWrapper();
                queryParent.eq(OrganizationalStructure::getOrganizationalId, organ.getParentId());
                queryParent.orderByDesc(OrganizationalStructure::getGmtModified);
                List<OrganizationalStructure> orglists = organizationalStructureMapper.selectList(queryParent);
                if (orglists.size() > 0) {
                    organ = orglists.get(0);
                }
                a++;
            }
        }
        return organ;
    }
    //2022-09-15 校验业态是否有效
    public boolean checkFormatId(Integer formatId,String channel){
        LambdaQueryWrapper<OrganizationalStructure> queryParent = new LambdaQueryWrapper();
        queryParent.eq(OrganizationalStructure::getOrganizationalId, formatId);
        queryParent.eq(OrganizationalStructure::getChannel, channel);
        queryParent.eq(OrganizationalStructure::getOrganizationalType, SystemConstant.ORGANIZATIONAL_STRUCTURE_TYPE_0);
        queryParent.and(Wrapper -> Wrapper.eq(OrganizationalStructure::getParentId,SystemConstant.ORGANIZATIONAL_PARENT_ID).or().eq(OrganizationalStructure::getParentId,formatId));
        return organizationalStructureMapper.selectCount(queryParent)>0;
    }
}
